// 登陆成功执行，刷新页面
function webViewDidLoad() { // eslint-disable-line
    location.reload();  // eslint-disable-line
}
var bb=123;
(function () {
    /* global ACT_RANDOM_HOST */
    /* global beginTime */
    /* global endTime */
    var $openRule = $('#openRule'), // 规则按钮
        // $btnShare = $('#shareEnlarge'),
        $btnRedpackage = $('#money'), // 红包按钮
        $overlay = $('#model'), // 遮照
        // $popRedPackage = $('#sec'), // 红包弹出框
        // $popUpdate = $('#sjtc'), // 升级提示框
        $popRuleBox = $('#rule'),
        $closeRule = $('#closeRule'), // 规则按钮
        $btnPlay = $('#btnPlay'), // 播放
        $btnBarrage = $('#btnBarrage'),
        $comment = $('#comment'), // 评论输入框
        $surplusNum = $('#surplusNum'), // 剩余多少个字
        $btnSend = $('#btnSend'), // 发送
        $boxDanMu = $('#boxDanMu'),
        $boxComment = $('#boxInput'), // 输入块
        $boxDanmuLoading = $('#boxDanmuLoading'), // 弹幕加载提示
        $boxDanmuError = $boxDanmuLoading.children('#danmuTextError'), // 弹幕加载失败提示
        videoE = document.getElementById('video'),
        userId = (+new Date()) + Math.random().toString(10).substring(2, 6), // 测试
        app_id = 'chath5',
        rId = '5555',
        name = '',
        // head = '',
        netState = true, // true 连接正常 false 网络断开
        firstAlert = 0, // 红包颜色状态
        // rowkey = '7324973133247419391',
        appKey = '80e93c3a398a1f39c4091ff0f8b64213',
        disconnectState = 'first',
        // danmu_color = '#8a7e6d',
        // winHeight = $(window).height(), // 获取当前页面高度
        is_android = (function () {
            var u = navigator.userAgent;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; // android终端
            return isAndroid;
        }());
    var nowTime = new Date().getTime();
    var myDanmuArr = [];
    var clientinfo = {};
    var userinfo = {};
    var inviteCode = null;
    var hasTaken = 0;
    var money = 0;
    var success = 0;
    var moneybuttonlock = false;
    var updateMoneyTimer = null;
    // 客户端时间    new Date().getTime()
    var ct = 0;    // eslint-disable-line
    var Page = function () { };
    Page.prototype = {
        init: function () {
            var scope = this;
            scope.isLogin();
            // scope.enterConnector(); // 测试
            scope.event();
            // setInterval(function(){
            // scope.testDanMu(); // 测试
            // },3000);
        },
        event: function () {
            var scope = this;
            window.addEventListener('online', monitoringNet);
            window.addEventListener('offline', monitoringNet);
            function monitoringNet() {
                if (navigator.onLine) {
                    alert('网络已恢复');
                    // console.log('monitoringNet', scope);
                    scope.enterConnector();
                } else {
                    alert('网络已断开');
                }
            }
            // 关闭页面时退出房间
            window.onbeforeunload = function () {
                pomelo.request('room.roomHandler.leave', function (data) {
                });
            };
            // 点击规则显示规则按钮
            $openRule.click(function () {
                $overlay.show();
                $popRuleBox.show();
            });
            // 点击关闭隐藏规则
            $closeRule.click(function () {
                $overlay.hide();
                $popRuleBox.hide();
            });
            var bfscrolltop = document.body.scrollTop, // 获取软键盘唤起前浏览器滚动部分的高度
                interval;
            $comment.focus(function () { // 当它获取焦点时触发事件
                interval = setInterval(function () { // 设置一个计时器，时间设置与软键盘弹出所需时间相近
                    document.body.scrollTop = document.body.scrollHeight;// 获取焦点后将浏览器内所有内容高度赋给浏览器滚动部分高度
                }, 100);
            }).blur(function () { // 设定输入框失去焦点时的事件
                clearInterval(interval);// 清除计时器
                // document.body.scrollTop = bfscrolltop;
                // 将软键盘唤起前的浏览器滚动部分高度重新赋给改变后的高度
            });
            $comment.bind('input', function () {
                // 最多15个字
                var $this = $(this),
                    val = $this.val();
                $surplusNum.text(15 - val.length);
            });
            $btnSend.click(function (e) {
                e.stopPropagation();
                document.body.scrollTop = bfscrolltop;
                $boxComment.hide();
                var surplusNum = $surplusNum.text(),
                    route = 'room.roomHandler.send',
                    commentVal = $comment.val();
                if (surplusNum < 0) {
                    alert('字数超出限制'); /* globals alert */
                } else if (surplusNum == 15) {
                    alert('您还没有输入评论');
                    return false;
                } else {
                    $comment.val('');
                    $surplusNum.text('15');
                    pomelo.request(route, {
                        msg: commentVal
                    }, function (data) {
                        if (data.code != 200) {
                            alert('弹幕发送失败，请稍后再试！');
                        } else {
                            myDanmuArr.unshift({ 'text': '<small>' + (name || '火星来客') + '：</small>' + commentVal });
                            alert('好一发弹幕~');
                        }
                    });
                }
            });

            // 点击输入块不隐藏输入块
            $boxComment.click(function (e) {
                e.stopPropagation();
            });
            $btnBarrage.click(function (e) {
                e.stopPropagation();
                if ($boxComment.is(':hidden')) {
                    $boxComment.show();
                    $comment.trigger('focus');
                } else {
                    $boxComment.hide();
                }
            });
            $(document).click(function () {
                $boxComment.hide();
            });
            // 点击屏幕加载视频
            // $(document).touchstart(function(){
            //     videoE.play();
            // });
            // JS绑定自动播放（操作window时，播放shipin）
            $(window).one('touchstart', function () {
                videoE.play();
            });
            // 点击播放按钮
            $btnPlay.click(function (e) {
                e.stopPropagation();
                if (!netState) {
                    alert('网络异常，视频无法加载');
                    return false;
                }
                videoE.play();
                $btnPlay.hide();
                if (!videoE.isPlayed) {
                    $btnPlay.prev().show();
                }
                scope.report('click6');
            });
            videoE.onclick = function () {
                videoE.pause();
                $btnPlay.show();
            };
            videoE.onpause = function () {
                $btnPlay.show();
            };
            videoE.ended = function () {
                $btnPlay.show();
            };
            videoE.onplay = function () {
                videoE.play();
                $btnPlay.hide();
            };
            videoE.onplay = function () {
                videoE.play();
                $btnPlay.hide();
            };
            videoE.ontimeupdate = function () {
                if (!videoE.isPlayed) {
                    // 当视频的currentTime大于0.1时表示黑屏时间已过，已有视频画面，可以移除浮层
                    if (!this.isPlayed && this.currentTime > 0.1) {
                        $btnPlay.prev().fadeOut(500);
                        videoE.isPlayed = !0;
                    }
                }
            };
            $('#closeSec').on('click', function () {
                $('#model').hide();
                $('#sec').hide();
            });
        },
        testDanMu: function () {
            var random = parseInt((Math.random() + '').substring(2)).toString(16);
            myDanmuArr.push({ 'text': '小敏' + random + '<small>进入了房间</small>！' });
        },
        queryEntry: function (uid, callback) {
            // var scope = this;
            /* globals pomelo */
            // callback('106.75.73.67', '5010');// 测试
            var route = 'gate.gateHandler.queryEntry';
            pomelo.init({
                host: '117.50.5.84', // 正式
                port: '3014',
                log: true
            }, function () {
                pomelo.request(route, {
                    uid: userId
                }, function (data) {
                    disconnectState = 'first';
                    pomelo.disconnect();
                    // console.log('queryEntry', JSON.stringify(data)); // 测试代码
                    if (data.code === 500) {
                        // console.log('queryEntry', data);
                        return;
                    }
                    callback(data.host, data.port);
                });
            });
        },
        enterConnector: function () {
            var scope = this;
            // name = name || '大王'; // 测试
            // var obj = {
            //     rid: rId,
            //     rowkey: rowkey,
            //     nn: name,
            //     lv: head,
            //     uid: userId,
            //     nickname: name,
            //     app_id: app_id,
            //     headpic:''
            // }
            // console.log('enterConnector'); // 测试
            scope.queryEntry(userId, function (host, port) {
                pomelo.init({
                    host: host,
                    port: port,
                    log: true
                }, function () {
                    var route = 'connector.entryHandler.entry';
                    var ts = Math.floor(parseInt(Date.now() / 1000 / 10));
                    var content = app_id + userId + ts + appKey;
                    var hash = md5(content).toString(); /* globals md5 */
                    var ticket = hash.toLowerCase();
                    pomelo.request(route, {
                        app_id: app_id,
                        ticket: ticket,
                        uid: userId,
                        nn: name,
                        rid: rId
                    }, function (data) {
                        disconnectState = 'second';
                        // console.log('enterConnector',JSON.stringify(data)); //测试代码
                        if (data.error) {
                            console.log('enterConnector', data.error);
                        } else {
                            scope.enterRoom();
                        }
                    });
                });
            });
        },
        enterRoom: function () {
            var scope = this,
                route = 'room.roomHandler.entry';
            pomelo.request(route, function (data) {
                // console.log('enterRoom', JSON.stringify(data)); // 测试代码
                if (data.code == 200) {
                    scope.listenEvent();
                }
            });
        },
        listenEvent: function () {
            var scope = this;
            $boxDanmuLoading.hide().children('.text-loading').hide().prev().hide();
            scope.renderDanmu(); // 渲染弹幕
            myDanmuArr.push({ 'text': name + '已进场！' });
            pomelo.on('onChatMsg', function (data) {
                // console.log('onChatMsg',data,new Date().getSeconds());
                if (data && data.length > 0) {
                    scope.showDanmu(data, 'onChatMsg');
                }
            });
            pomelo.on('onUserEnter', function (data) {
                if (data && data.length > 0) {
                    scope.showDanmu(data, 'onUserEnter');
                }
            });
            pomelo.on('disconnect', function (reason) {
                // console.log('reason='+reason+';disconnectState='+disconnectState);
                if (disconnectState === 'second') {
                    $boxDanmuError.show().parent().show();
                    scope.enterConnector();
                }
            });
        },
        showDanmu: function (data, type) {
            var scope = this;
            for (var i = 0, len = data.length; i < len; i++) {
                var nickname = data[i].nn ? data[i].nn + '' : '';
                if (!isNaN(nickname)) {
                    if (nickname.length == 11) {
                        nickname = scope.replaceStrByPosition(nickname, 3, 7, '****');
                    }
                }
                if (type === 'onUserEnter') {
                    myDanmuArr.push({ 'text': nickname + '已进场！', quick: 1000 });
                } else {
                    myDanmuArr.push({ 'text': '<small>' + nickname + '：</small>' + data[i].msg });
                }
                // if (data.type == 4) {
                // }
            }
        },

        renderDanmu: function () {
            var scope = this;
            var opt = {
                minSpeed: 3000,
                maxSpeed: 4000,
                color: ['#8a7e6d'],
                fontSize: ['12px']
            };
            var topArr = [8, 43, 78, 113];
            var topIdx = 0;
            var left = $boxDanMu.width();
            var $cont = $('#danmu-wrap');
            var danmuDomArr = [];
            var render = function () {
                var i = 0;
                var len = myDanmuArr.length < 4 ? myDanmuArr.length : Math.ceil(myDanmuArr.length / 3);
                var item = null;
                var speed = null;
                var delay = null;
                var top = 0;
                var $span = '';
                // console.log('len:', len);
                for (i = 0; i < len; i++) {
                    // 发弹幕
                    item = myDanmuArr.shift();
                    var style = 'position:absolute;white-space:nowrap; left:' + left + 'px;color:' + (item.color || opt.color[0]) + ';font-size:' + (item.fontSize || opt.fontSize[0]) + ';';
                    if (item.quick) {
                        speed = (scope.setRandomNum(opt.minSpeed - item.quick, opt.maxSpeed - item.quick) / 1000).toFixed(1);
                    } else {
                        speed = (scope.setRandomNum(opt.minSpeed, opt.maxSpeed) / 1000).toFixed(1); // 获取范围内随机速度
                    }
                    delay = (scope.setRandomNum(0, 1000) / 1000).toFixed(1); // 获取范围内随机延迟时间
                    if (topIdx >= topArr.length) {
                        topIdx = 0;
                    }
                    // console.log('speed:', speed)
                    top = topArr[topIdx++];
                    style += 'top:' + top + 'px;-webkit-transition:all ' + speed + 's linear;transition:all ' + speed + 's linear;-webkit-transition-delay:' + delay + 's;transition-delay:' + delay + 's;';
                    $span = $('<span class="text" style = "' + style + '">' + item.text + '</span>');
                    $cont.append($span);
                    scope.moveing($span);
                }
                setTimeout(function () {
                    render();
                    $cont.children().each(function () {
                        var $this = $(this);
                        var offsetLeft = $this.offset().left;
                        if (offsetLeft < 0 && Math.abs(offsetLeft) + $cont.offset().left > $this.width()) {
                            // $this.remove();
                            //  延迟插入队列中，尽量保证弹幕全部走完再做删除。
                            setTimeout(function () {
                                danmuDomArr.push($this);
                            }, 1000);
                            $.each(danmuDomArr, function (i, $dom) {
                                $dom.remove();
                            });
                        }
                    });
                    // 当堆栈中弹幕数量超过了48条，就从前面删除到48条。保证堆栈中不超过48条弹幕。
                    while (myDanmuArr.length > 48) {
                        myDanmuArr.shift();
                    }
                }, 1000);
            };
            render();
        },

        moveing: function ($span) {
            var left = parseInt($boxDanMu.width()) + parseInt($span.innerWidth());
            // console.log(-left, left);
            $span.css({
                '-webkit-transform': 'translate3d(' + (-left) + 'px, 0, 0)',
                'transform': 'translate3d(' + (-left) + 'px, 0, 0)'
            });
        },

        setRandomNum: function (a, b) {
            return parseInt(a + (b - a) * Math.random());
        },

        /**
         * 打乱数组
         * @param  {[type]} arr 目标数组
         * @return {[type]}     [description]
         */
        dislocateArr: function (arr) {
            return arr.sort(function () {
                return 0.5 - Math.random();
            });
        },

        isLogin: function () {
            var scope = this;
            $.ttapp.userinfo(function (ret) {
                userinfo = ret;
                if (ret.Accid <= 0) {
                    entry();    // eslint-disable-line
                    $('#login_pxh').click(function () {
                        $.ttapp.login();
                        // $('#loginOverlay').hide().next().hide(); // 测试
                    });
                    return false;
                } else {
                    inviteCode = ret.Accid.toString();
                    inviteCode = scope.yingshe(inviteCode);
                    head = ret.Image;   // eslint-disable-line
                    name = ret.Nick || '' + ret.Mobile || '头条用户' + Math.random().toString().split('.')[1].substr(0, 9);
                    if (!isNaN(name)) {
                        if ((name + '').length === 11) {
                            name = scope.replaceStrByPosition(name, 3, 7, '****');
                        }
                    }

                    $.ttapp.clientinfo(function (ret) {
                        clientinfo = ret;
                        if (is_android == true && clientinfo.Version < '1.9.7') {
                            $('#model,.sjtc').show();
                            $('.sj').click(function () {
                                window.location.href = 'https://down.hao1982.com/android/qdb/h5/dongfangtoutiao_bdhb_updsp.apk';
                            });
                        } else if (is_android != true && clientinfo.Version < '1.9.7') {
                            $('#model,.sjtc').show();
                            $('.sj').click(function () {
                                window.location.href = 'https://itunes.apple.com/cn/app/dong-fang-tou-tiao-xin-wen/id1030220577';
                            });
                        }

                        // 获取服务器时间
                        ct = new Date().getTime();
                    });
                    scope.enterConnector();
                    scope.counterDown();
                    scope.redState();

                    $('#money').unbind('click');
                    var siTimer = setInterval(function () {
                        if (moneybuttonlock) {
                            siTimer && clearInterval(siTimer);
                            $('#money').bind('click', function () {
                                if (nowTime < beginTime) {
                                    alert('活动时间未到');
                                } else if (nowTime >= beginTime) {
                                    if (success > 0) {
                                        $('#model').hide();
                                        $('#sec').hide();
                                        scope.redState(3);
                                        window.location.href = '6.html?j=' + success;
                                    } else if (success == 0) {
                                        if (nowTime < endTime && hasTaken == 0) {
                                            $('#model').show();
                                            $('#sec').show();
                                            $('#cross').attr('href', '6.html?j=-1');
                                            $('#cross').show();
                                            $('#flower').hide();
                                        } else {
                                            $('#model').show();
                                            $('#sec').show();
                                            $('#cross').attr('href', '6.html?j=-1');
                                            $('#cross').show();
                                            $('#flower').hide();
                                            $('#open').hide();
                                            // $('#content p').eq(1).text('');
                                            $('#content p').eq(1).hide();
                                            $('#content p').eq(2).text('手慢了，红包已抢完');
                                            // $('#adBtn').show();
                                            // scope.report('showAd1');
                                        }
                                    }
                                }
                                scope.report('click4');
                            });
                        }
                    }, 200);

                    // // 长按动画
                    // $('#open').on('contextmenu', function (e) {
                    //     e.preventDefault();
                    // })
                    // $('#open').on('touchstart', function () {
                    //     $(this).addClass('touched')
                    // })
                    // $('#open').on('touchend', function () {
                    //     $(this).removeClass('touched')
                    // })
                    // 点击开
                    var flag = true;
                    $('#open').on('click', function (event) {
                        var PARAM_EMPTY = 'null';
                        if (flag) {
                            flag = false;
                            $('#open').animate({ opacity: 0 }, 10);
                            $('#round').show();
                            // $('#open').addClass('opened');
                            // $('.coin-round').delay(200).show();
                            $.ajax({
                                url: '//h5act.dftoutiao.com/appact/songhongbao/take.php',
                                // url: '//test-h5act.dftoutiao.com/appact/songhongbao/take.php',// 测试
                                timeout: 5000,
                                dataType: 'jsonp',
                                jsonpCallback: 'callback',
                                data: {
                                    accid: userinfo.Accid,
                                    nick: userinfo.Nick,
                                    i: clientinfo.IMEI ? clientinfo.IMEI : PARAM_EMPTY,
                                    o: (clientinfo.OEM && clientinfo.Plantform) ? (clientinfo.OEM + (clientinfo.Plantform == 'android' ? 'Android' : 'IOS')) : PARAM_EMPTY,
                                    q: clientinfo.QidWithTime ? clientinfo.QidWithTime : (clientinfo.Qid ? clientinfo.Qid : PARAM_EMPTY),
                                    v: clientinfo.Version ? clientinfo.Version : PARAM_EMPTY,
                                    m: clientinfo.Machine ? clientinfo.Machine : PARAM_EMPTY,
                                    p: clientinfo.Plantform ? clientinfo.Plantform : PARAM_EMPTY
                                },
                                success: function (res) {
                                    var status = res.status; // 状态
                                    var msg = res.msg; // 消息
                                    // setTimeout(function () {
                                    if (status == '0') {
                                        money = res.m; // 钱
                                        // hasTaken = 1;
                                        success = res.m;
                                        window.location.href = '6.html?j=' + success;
                                        $('#model').hide();
                                        $('#sec').hide();
                                    } else {
                                        $('#cross').attr('href', '6.html?j=-1');
                                        $('#cross').show();
                                        $('#flower').hide();
                                        // $('#content p').eq(1).text('');
                                        $('#content p').eq(1).hide();
                                        $('#content p').eq(2).text(msg);
                                        // $('#adBtn').show();
                                        // scope.report('showAd1');
                                    }
                                    $('#open').hide();
                                    $('#round').hide();
                                    // $('.coin-round').hide();
                                    // }, 800)
                                },
                                error: function (data) {
                                    $('#model').show();
                                    $('#sec').show();
                                    $('#cross').attr('href', '6.html?j=-1');
                                    $('#cross').show();
                                    $('#flower').hide();
                                    $('#open').hide();
                                    $('#round').hide();
                                    // $('.coin-round').hide();
                                    // $('#content p').eq(1).text('');
                                    $('#content p').eq(1).hide();
                                    $('#content p').eq(2).text('当前抢红包人数过多,请稍后再试');
                                    // $('#adBtn').show();
                                    // scope.report('showAd1');
                                    return false;
                                },
                                complete: function (XMLHttpRequest, status) { // 请求完成后最终执行参数
                                    if (status == 'timeout') { // 超时,status还有success,error等值的情况
                                        alert('请求超时');
                                        $('#round').hide();
                                        // $('.coin-round').hide();
                                    }
                                }
                            });
                            scope.report('click2');
                        }
                    });

                    // 点击试试看
                    $('#adBtnClick').on('click', function (event) {
                        window.location.href = '//cfg.aiclicash.com/hdjump?iclicashid=7314760';
                        scope.report('clickAd1');
                    });

                    // 奖金池
                    ; (function () {
                        $.ajax({
                            type: 'GET',
                            url: '//h5act2.dftoutiao.com/appact/songhongbao/enter.php?accid=' + userinfo.Accid,
                            // url: '//test-h5act2.dftoutiao.com/appact/songhongbao/enter.php?accid=' + userinfo.Accid, // 测试
                            dataType: 'jsonp',
                            jsonp: 'jsonp',
                            jsonpCallback: 'callback',
                            success: function (res) {
                                // $('#totalmoney').text(res.total);
                                hasTaken = res.hasTaken;
                                if (!res.total) {
                                    $('#totalmoney').text('----');
                                } else {
                                    scope.totalmoney(res.total);
                                }
                                // $('#headImg').attr('src', res.winnerof288);
                                if (res.success > 0) {
                                    success = res.success;
                                }
                                moneybuttonlock = true;
                                // _this.lock = false;
                            },
                            error: function () { },
                            complete: function () {
                                moneybuttonlock = true;
                            }
                        });
                    }());
                    updateMoneyTimer = setInterval(function () {
                        $.ajax({
                            type: 'GET',
                            url: '//h5act2.dftoutiao.com/appact/songhongbao/enter.php?accid=' + userinfo.Accid, // 正式
                            dataType: 'jsonp',
                            jsonp: 'jsonp',
                            jsonpCallback: 'callback',
                            success: function (res) {
                                hasTaken = res.hasTaken;
                                if (!res.total) {
                                    $('#totalmoney').text('----');
                                } else {
                                    scope.totalmoney(res.total);
                                }
                                // $('#headImg').attr('src', res.winnerof288);
                                if (res.success > 0) {
                                    success = res.success;
                                }
                                moneybuttonlock = true;
                                // _this.lock = false;
                            },
                            error: function () { },
                            complete: function () {
                                moneybuttonlock = true;
                            }
                        });
                    }, 5000);
                }

                $('#cross').click(function () {
                    scope.report('click5');
                });

                // 点击分享扩大奖金池
                $('#shareEnlarge').click(function () {
                    var j = $('#money strong').text();
                    $.ttapp.share({
                        // shareUrl:'http://resources.dftoutiao.com/day20/hongbaoshare/redpackageh5.html?f=93014&u='+inviteCode+'&j='+j,
                        shareUrl: 'http://' + ACT_RANDOM_HOST[parseInt(Math.random() * ACT_RANDOM_HOST.length)] + '/qianghongbao/redpackageh5.html?f=93014&u=' + inviteCode + '&j=' + j, // 正式
                        // shareUrl: 'https://test-kp.dftoutiao.com/qianghongbao/outside1?f=93014&u=' + inviteCode + '&j=' + j,  // 测试
                        // shareUrl: 'https://test-kp.dftoutiao.com/qianghongbao/redpackageh5.html?f=93014&u=' + inviteCode + '&j=' + j,  //测试
                        shareTitle: '东方头条狂发百万现金红包，今晚8点准时开抢！', // 分享标题
                        shareDes: '每多1人参加，现金池再加1元', // 分享描述
                        // shareImg: 'https://resources.dftoutiao.com/songheng/toutiao/shb/share/shb2_share_logo.png'  //分享图片
                        shareImg: 'http://resources.dftoutiao.com/hongbaov2/img/v3/thumble.png'
                    });
                    scope.report('click1');
                });

                scope.report('show');
            });
        },
        getQueryString: function (name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        },
        // 上报统计
        report: function (type) {
            var PARAM_EMPTY = 'null';
            var scope = this;
            var road = 'app';
            if (scope.getQueryString('push')) {
                road = '14';
            }
            var statisData = {
                'uid': clientinfo.IMEI ? clientinfo.IMEI : PARAM_EMPTY,
                'from': 'app',
                'softname': (clientinfo.OEM && clientinfo.Plantform)
                    ? (clientinfo.OEM + (clientinfo.Plantform == 'android' ? 'Android' : 'IOS'))
                    : PARAM_EMPTY,
                'appqid': clientinfo.QidWithTime ? clientinfo.QidWithTime : (clientinfo.Qid ? clientinfo.Qid : PARAM_EMPTY),
                'ttaccid': userinfo.Accid ? userinfo.Accid : PARAM_EMPTY,
                'thisurl': window.location.href,
                'actentryid': road,
                'actid': 'robredpack',
                'materialid': 'zhangjingchu',
                'type': type,
                'loginid': userinfo.Accid ? userinfo.Accid : PARAM_EMPTY,
                'softtype': 'toutiao',
                'apptypeid': clientinfo.OEM ? clientinfo.OEM : PARAM_EMPTY,
                'ver': clientinfo.Version ? clientinfo.Version : PARAM_EMPTY,
                'os': clientinfo.Plantform ? clientinfo.Plantform : PARAM_EMPTY,
                'deviceid': clientinfo.IMEI ? clientinfo.IMEI : PARAM_EMPTY
            };

            $.ajax({
                url: '//stinvi.dftoutiao.com/appstatistics/appact',
                // url: 'http://123.59.60.170/appstatistics/appact', // 测试
                data: statisData,
                type: 'GET',
                dataType: 'jsonp',
                jsonp: 'jsonpcallback',
                timeout: 5000,
                success: function (response) {
                    // console.log(response);
                }
            });
        },
        totalmoney: function (total) {
            var scope = this;
            if (nowTime >= beginTime) { // eslint-disable-line
                $('#totalmoney').html('<span class="timer" id="count-number" data-from="' + total + '" data-to="' + total + '" data-speed="5000" ></span>');
            } else if (nowTime < beginTime) { // eslint-disable-line
                var dataTo = total;
                var dataFrom = parseInt(scope.getCookie('dataFrom')) < dataTo ? parseInt(scope.getCookie('dataFrom')) : (total - 1);
                scope.setCookie('dataFrom', dataTo);
                $('#totalmoney').html('<span class="timer" id="count-number" data-from="' + dataFrom + '" data-to="' + dataTo + '" data-speed="5000" ></span>');
            }
            $('.timer').each(count);  // eslint-disable-line
        },
        counterDown: function () {
            var scope = this;
            // 倒计时js
            var timer1 = setInterval(function () {
                // nowTime += 1000;
                nowTime = new Date().getTime();
                if (nowTime < beginTime) {  // eslint-disable-line
                    var s = parseInt((beginTime - nowTime) / 1000);  // eslint-disable-line
                    // var d = scope.fillZero(parseInt(s / 86400));
                    s %= 86400;
                    var h = scope.fillZero(parseInt(s / 3600));
                    s %= 3600;
                    var m = scope.fillZero(parseInt(s / 60));
                    s = scope.fillZero(s % 60);
                    $('#hour').text(h);
                    $('#minute').text(m);
                    $('#second').text(s);
                    scope.redState(1);
                    if (beginTime - nowTime < 30000) {
                        clearInterval(updateMoneyTimer);
                    }
                } else if (beginTime <= nowTime && nowTime < endTime) {  // eslint-disable-line
                    $('#hour').text('00');
                    $('#minute').text('00');
                    $('#second').text('00');
                    moneybuttonlock = true;
                    scope.redState(2);
                } else if (nowTime >= endTime) {  // eslint-disable-line
                    $('#hour').text('00');
                    $('#minute').text('00');
                    $('#second').text('00');
                    scope.redState(3);
                    // $('#me').show();
                    // $('#ulName').addClass('endShow');
                    moneybuttonlock = true;
                    clearInterval(timer1);
                    clearInterval(updateMoneyTimer);
                }
            }, 1000);
        },
        redState: function (param) { // param 参数 活动前1  活动中2  活动结束3
            if (param == 1) {
                $btnRedpackage.removeClass('active').addClass('disabled');
                $('.text2').text('暂未开始');
            } else if (param == 2) {
                if (money > 0 || hasTaken > 0) {
                    $btnRedpackage.removeClass('active').addClass('disabled');
                    $('.text2').text('红包已领取');
                } else {
                    firstAlert++;
                    $btnRedpackage.removeClass('disabled').addClass('active');
                    $('.text2').text('活动进行中');
                    if (firstAlert == 1) {
                        $('#model').show();
                        $('#sec').show();
                        $('#flower').show();
                    }
                }
            } else if (param == 3) {
                $btnRedpackage.removeClass('active').addClass('disabled');
                if (money > 0 || hasTaken > 0) {
                    $('.text2').text('今日红包已领取');
                } else {
                    $('.text2').text('今日红包已瓜分完');
                }
            }
        },
        replaceStrByPosition: function (string, start, end, newString) {
            if (string) {
                var charArr = string.split(''),
                    len = charArr.length;
                if (len < start) {
                    return '';
                }
                if (end >= len) {
                    end = len - 1;
                }
                for (var i = start, j = 0; i < end; i++) {
                    charArr[i] = newString.charAt(j);
                    j = j + 1;
                }
                return charArr.join('');
            }
        },
        fillZero: function (n) {
            return n < 10 ? '0' + n : n;
        },
        setCookie: function (name, value) {
            var Days = 30;
            var exp = new Date();
            exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
            document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString();
        },
        getCookie: function (name) {
            var arr, reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
            if (arr = document.cookie.match(reg)) { return unescape(arr[2]); } else { return null; }  // eslint-disable-line
        },
        delCookie: function (name) {
            var scope = this;
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval = scope.getCookie(name);
            if (cval != null) { document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString(); }
        },
        yingshe: function (string) {
            var arr = [];
            for (var i = 0; i < string.length; i++) {
                switch (string[i]) {
                case '0':
                    arr.push('7');
                    break;
                case '1':
                    arr.push('4');
                    break;
                case '2':
                    arr.push('8');
                    break;
                case '3':
                    arr.push('2');
                    break;
                case '4':
                    arr.push('5');
                    break;
                case '5':
                    arr.push('1');
                    break;
                case '6':
                    arr.push('9');
                    break;
                case '7':
                    arr.push('3');
                    break;
                case '8':
                    arr.push('0');
                    break;
                case '9':
                    arr.push('6');
                    break;
                default:
                    return false;
                }
            }
            return arr.join('');
        },
        /**
         * 动态加载js文件
         * @param  {string}   url      js文件的url地址
         * @param  {Function} callback 加载完成后的回调函数
         */
        getScript: function (url, callback, element) {
            var head = document.getElementsByTagName('head')[0],
                js = document.createElement('script');
            js.setAttribute('type', 'text/javascript');
            js.setAttribute('src', url);
            if (element) {
                element.appendChild(js);
            } else {
                head.appendChild(js);
            }
            // 执行回调
            var callbackFn = function () {
                if (typeof callback === 'function') {
                    callback();
                }
            };
            js.onload = function () {
                callbackFn();
                js.parentNode.removeChild(js);
            };
        }
    };
    $(function () {
        try {
            FastClick.attach(document.body);    // eslint-disable-line
        } catch (e) { }
        var page = new Page();
        page.init();
    });
}());